﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace System.Windows.Controls
{
    public static class PageExtensions
    {
        static Dictionary<string, object> _state = new Dictionary<string,object>();
        public static void StoreSessionVariable(this Page page, string name, object value)
        {
            if (_state.ContainsKey(name))
            {
                _state[name] = value;
            }
            else
            {
                _state.Add(name, value);
            }
        }

        public static T ReadSessionVariable<T>(this Page page, string name)
        {
            if (_state.ContainsKey(name))
            {
                return (T)_state[name];
            }
            return default(T);
        }

        public static string GetQueryString(this Page page, string name)
        {
            try
            {
                string url_string = page.NavigationService.Source.OriginalString;
                string[] parts = url_string.Split('?');
                string[] querystring = parts[1].Split('&');
                foreach (string name_value_pair in querystring)
                {
                    string[] nvpair_parts = name_value_pair.Split('=');
                    if (nvpair_parts[0].Trim() == name)
                        return nvpair_parts[1];
                }
            }
            catch (Exception ex)
            {

            }
            return "";
        }

        public static bool HasQueryString(this Page page, string name)
        {
            try
            {
                string url_string = page.NavigationService.Source.OriginalString;
                string[] parts = url_string.Split('?');
                string[] querystring = parts[1].Split('&');
                foreach (string name_value_pair in querystring)
                {
                    string[] nvpair_parts = name_value_pair.Split('=');
                    if (nvpair_parts[0].Trim() == name)
                        return true;
                }
            }
            catch (Exception ex)
            {

            }
            return false;
        }
    }
}
